package com.commerceE.common.dao;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcDaoSupport;

import com.commerceE.common.exception.DaoException;

public class NamedParamterJdbcDao extends NamedParameterJdbcDaoSupport {

	/**
	 * @param query
	 * @param paramMap
	 * @return
	 * @throws DaoException
	 */
	public List<Map<String, Object>> executeJdbcQuery(String query,
			Map<String, Object> paramMap) throws DaoException {
		String errorMsg = "";
		List<Map<String, Object>> resultList = new ArrayList<Map<String, Object>>();
		try {
			resultList = getNamedParameterJdbcTemplate().queryForList(query,
					paramMap);
		} catch (DataAccessException e) {
			errorMsg = "Failed to excute the query " + query
					+ " . The system error is :" + e.getMessage();
			logger.error(errorMsg);
			throw new DaoException(errorMsg);
		} catch (Exception e) {
			errorMsg = "Failed to excute the query " + query
					+ " . The system error is :" + e.getMessage();
			logger.error(errorMsg);
			throw new DaoException(errorMsg);
		}
		return resultList;
	}

	/**
	 * @param query
	 * @param paramMap
	 * @return
	 * @throws DaoException
	 */
	public int executeJdbcUpdate(String query, Map<String, Object> paramMap)
			throws DaoException {
		int count = 0;
		String errorMsg = "";
		try {
			count = getNamedParameterJdbcTemplate().update(query, paramMap);
		} catch (DataAccessException e) {
			errorMsg = "Failed to excute the query " + query
					+ " .\r\n The system error is :" + e.getMessage();
			logger.error(errorMsg);
			throw new DaoException(errorMsg);
		} catch (Exception e) {
			errorMsg = "Failed to excute the query " + query
					+ " .\r\n The system error is :" + e.getMessage();
			logger.error(errorMsg);
			throw new DaoException(errorMsg);
		}
		return count;
	}

	/**
	 * @param query
	 * @param paramMap
	 * @return
	 * @throws DaoException
	 */
	public int executeSimpleQuery(String query, Map<String, String> paramMap)
			throws DaoException {
		int count = 0;
		String errorMsg = "";
		try {
			count = getNamedParameterJdbcTemplate()
					.queryForInt(query, paramMap);
		} catch (DataAccessException e) {
			errorMsg = "Failed to excute the query " + query
					+ " .\r\n The system error is :" + e.getMessage();
			logger.error(errorMsg);
			throw new DaoException(errorMsg);
		} catch (Exception e) {
			errorMsg = "Failed to excute the query " + query
					+ " .\r\n The system error is :" + e.getMessage();
			logger.error(errorMsg);
			throw new DaoException(errorMsg);
		}
		return count;
	}

}
